<template>
	<div class="typer">
		<div class="typer-content">
			<!-- 动态变化的内容-->
			<span class="typer-dynamic">
				<span class="typer-static">{{ prefix }}&nbsp;</span>
				<span class="cut" :style="{ color: color }">
					<span class="word" v-for="(letter, index) in state.words" :key="index">{{ letter }}</span>
				</span>
				<!-- 模拟光标-->
				<span class="typer-cursor" :style="{ backgroundColor: color }"></span>
			</span>
		</div>
	</div>
</template>
<script lang="ts" setup>
import { PropType } from "vue";

const props = defineProps({
	prefix: String,
	color: {
		type: String,
		default: "#333333"
	},
	dataList: {
		type: Array as PropType<string[]>,
		default() {
			return [];
		}
	}
});
const state = reactive({
	words: [] as string[], //字母数组push，pop的载体
	letters: [] as string[], //str分解后的字母数组
	str: "",
	order: 1 //表示当前是第几句话,
});
watch(
	() => state.order,
	() => {
		//监听order值的变化，改变str的内容
		let index = state.order % props.dataList.length;
		state.str = props.dataList[index];
	}
);
onMounted(() => {
	state.str = props.dataList?.[0] || "";
	begin();
});
//开始输入的效果动画
const begin = () => {
	state.letters = state.str.split("");
	for (let i = 0; i < state.letters.length; i++) {
		setTimeout(write(i), i * 100);
	}
};
//开始删除的效果动画
const back = () => {
	let L = state.letters.length;
	for (let i = 0; i < L; i++) {
		setTimeout(wipe(i), i * 50);
	}
};
//输入字母
const write = (i: number) => {
	return () => {
		let L = state.letters.length;
		state.words.push(state.letters[i]);
		/*如果输入完毕，在5s后开始删除*/
		if (i == L - 1) {
			setTimeout(() => {
				back();
			}, 5000);
		}
	};
};
//擦掉(删除)字母
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const wipe = (i: number) => {
	return () => {
		state.words.pop();
		// state.words.pop(state.letters[i]);
		/*如果删除完毕，在300ms后开始输入*/
		if (state.words.length == 0) {
			state.order++;
			setTimeout(() => {
				begin();
			}, 300);
		}
	};
};
</script>

<style scoped lang="scss">
/* stylelint-disable-next-line scss/dollar-variable-pattern */
.typer {
	box-sizing: border-box;
	.typer-content {
		display: inline-flex;
		.typer-dynamic {
			position: relative;
		}
		.typer-cursor {
			display: inline-flex;
			width: 2px;
			height: 18px;
			margin-left: 5px;
			animation: flash 1.5s linear infinite;
		}
	}
}
</style>
